package mytest.bb;

import java.util.Random;

import sde.actor.Actor;
import sde.actor.Message;

public class Producer extends Actor {
	private static class Init extends Message{}
	
	private static class Generate extends Message{}
	
	private static int ID = 0;
	
	private final int id;
	
	private int num;//numero che genera il produttore

	private final byte CREATED = 0, PRODUCING = 1, WAITING = 2;
	
	private BufferIF buffer;
	
	private Random random = new Random();
	
	public Producer(){
		id=++ID;
		become(CREATED);
	}
	
	public void init(BufferIF buffer, int num){
		this.buffer = buffer;
		this.num = num;
		send(new Init());//lo mando a me stesso
	}

	@Override
	public void handler(Message m) {
		switch(currentStatus()){
		case CREATED:
			if(m instanceof Init){
				System.out.println("Producer #"+id+
		                 " generates item# "+num+" @"+now());
				buffer.send(new BufferIF.Put(this, num));
				become(WAITING);
			}
			break;
		case PRODUCING:
			if (m instanceof Generate) {
				System.out.println("Producer #"+id+
		                 " generates item# "+num+" @"+now());
				buffer.send(new BufferIF.Put(this, num));
				become(WAITING);
			}
			break;
		case WAITING:
			if (m instanceof BufferIF.Put.Reply) {
				send(new Generate(), now() + random.nextDouble() * 100);
				become(PRODUCING);
			}
			break;
		}
	}
}
